<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Agenda-item Invoegen</title>
<link href="opmaak.css" rel="stylesheet" type="text/css" media="screen" />
  
  <link type="text/css" href="themes/base/ui.all.css" rel="stylesheet" />
  <script type="text/javascript" src="jquery-1.3.2.min.js"></script>
  <script type="text/javascript" src="ui/ui.core.js"></script>
  <script type="text/javascript" src="ui/ui.datepicker.js"></script>
  <script type="text/javascript" src="ui/ui.slider.js"></script>
  <script type="text/javascript" src="ui/i18n/ui.datepicker-nl.js"></script>

<script type="text/javascript">
	$(document).ready(function(){ 
	
	var d = new Date();
	var curr_hour = d.getHours();
	var curr_min = d.getMinutes();
	if (curr_min/60 < 0.75 && curr_min/60 > 0.25)
	{
		curr_min = 30;
		next_min = '00';
		next_hour = curr_hour+1;
	}
	else
	{
		curr_min = '00';
		next_min = '30';
		next_hour = curr_hour;
	}
	var timevalue = curr_hour+(curr_min/60);

	
	$('#begintijd').before('<div id="tijd">'+curr_hour+':'+curr_min+' uur</div>');
	$('#eindtijd').before('<div id="etijd">'+next_hour+':'+next_min+' uur</div>');
	if (curr_hour < 10)
		{
			curr_hour = '0'+curr_hour;
		}
		if (next_hour < 10)
		{
			next_hour = '0'+next_hour;
		}
	$('#begintijd input').attr("value", curr_hour+":"+curr_min);
	$('#eindtijd input').attr("value", next_hour+":"+next_min);
	$('#begintijd, #eindtijd').css({ "margin-top" : "5px" });
	$("#begindatum").datepicker({ dateFormat: 'yy-mm-dd' }, $.datepicker.regional['nl']);
	$("#einddatum").datepicker({ dateFormat: 'yy-mm-dd' }, $.datepicker.regional['nl']);
	 
	$('#begintijd').slider({
	value: timevalue,
	max: 23.5,
	step: 0.5,	
	slide: function(event, ui) 
	{
		$("#tijd").remove();
		if (Math.round(ui.value) == ui.value)
		{
			var hours = Math.round(ui.value);
			var minutes = '00'
		}
		else
		{
			var hours = Math.round(ui.value)-1;
			var minutes = '30'
		}
		$('#begintijd').before('<div id="tijd">'+hours+':'+minutes+' uur</div>');
		if (hours < 10)
		{
			hours = '0'+hours;
		}
		$('#begintijd input').attr("value", hours+":"+minutes);
		$('#tijd').css({ "margin-top" : "5px" });
	}
	});
	$('#eindtijd').slider({
	value: timevalue+0.5,
	max: 23.5,
	step: 0.5,	
	slide: function(event, ui) 
	{
		$("#etijd").remove();
		if (Math.round(ui.value) == ui.value)
		{
			var hours = Math.round(ui.value);
			var minutes = '00'
		}
		else
		{
			var hours = Math.round(ui.value)-1;
			var minutes = '30'
		}
		$('#eindtijd').before('<div id="etijd">'+hours+':'+minutes+' uur</div>');
		if (hours < 10)
		{
			hours = '0'+hours;
		}
		$('#eindtijd input').attr("value", hours+":"+minutes);
		$('#etijd').css({ "margin-top" : "5px" });
	}
	});
	
	$('#etijd, #tijd').css({ "margin-top" : "5px" });
	});
	function laadscherm()
	{
 		$('body').empty();
		$('body').append('<img src="http://www.club-connect.nl/hyvessync/images/loading.gif" title="loading" alt="loading" />')
	}
</script>
</head>

<body>
<?php
require_once("database_inc.php");
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Calendar');

// STAP 1 :: verbinding maken
			$db = mysql_connect($server,$gebruikersnaam, $password);
				
			// STAP 2 :: db selecteren
			mysql_select_db($database, $db);
			
			// STAP 3 :: making Query
			$sql = "SELECT * FROM users WHERE hyvesID = '".$_SESSION['hyvesid']."' ";
		
			// STAP 4 :: use QUery
			$result = mysql_query($sql, $db);
			//get google token
			$regel = mysql_fetch_assoc($result);
			$client = Zend_Gdata_AuthSub::getHttpClient($regel['googleAuthSubToken']);
		//mking conection with google calander
		$gdataCal = new Zend_Gdata_Calendar($client);
			try
			{
			  $calFeed = $gdataCal->getCalendarListFeed();
			}
			catch(Zend_Gdata_App_HttpException $e) 
			{
			 echo 'Er kan geen verbinding gemaakt worden met Google Calendar: '.$e->getMessage().'. Probeer het later nog eens';       
			} 
      //looking witch calander u can edit
      foreach ($calFeed as $calendar) 
		{
			 if($calendar->accessLevel == 'owner' || $calendar->accessLevel == 'editor')
			 {
			   $linkies[] = array($calendar->getAlternateLink()->href, $calendar->title->text);
			 } 
		}
//error treatment
if (isset($_POST['Submit'])) 
{

	
		if(empty($_POST['Bdatum']))
						{
							$error .= '<li class="error">Voer alstublieft uw Begin datum in</li><br />'; 
						}
		if(empty($_POST['Btijd']))
						{
							$error .= '<li class="error">Voer alstublieft uw Begin tijd in</li><br />'; 
						}
		if(empty($_POST['Edatum']))
						{
							$error .= '<li class="error">Voer alstublieft uw Eind datum in</li><br />'; 
						}
		if(empty($_POST['Etijd']))
						{
							$error .= '<li class="error">Voer alstublieft uw Eind tijd in</li><br />'; 
						}
		//exploding time and date's			
		$tijdarray = explode (':', $_POST['Btijd'] );
		$datumarray = explode ('-', $_POST['Bdatum']);	
		
		$Etijdarray = explode (':', $_POST['Etijd'] );
		$Edatumarray = explode ('-', $_POST['Edatum']);
	
		$Bstamp = mktime  ($tijdarray[0], $tijdarray[1] ,00, $datumarray[1] , $datumarray[2] , $datumarray[0]);
		
		$Estamp = mktime  ($Etijdarray[0], $Etijdarray[1] ,00, $Edatumarray[1] , $Edatumarray[2] , $Edatumarray[0]);
		if ($Estamp < $Bstamp)
						{
							$error = '<li class="error">Uw data of tijdsaanduiding is incorrect ingevuld.</li><br />'; 
						}
						
		if(empty($error))
			{
			//making variables for inserting to calander
			$Wat = 				$_POST['Wat'];
			$Beschrijving = 	$_POST['Beschrijving'];
			$Waar =				$_POST['Waar'];
			$Bdatum = 			$_POST['Bdatum'];
			$Btijd =			$_POST['Btijd'];
			$Edatum = 			$_POST['Edatum'];
			$Etijd =			$_POST['Etijd'];
			
			$Reminder =		$_POST['Reminder'];	
			$Tijd	  =	(int) $_POST['Tijd'];
			$Time	  = 		$_POST['Time'];
			$kalender = 		$_POST['Kalender'];
			
			  	//making a event for inserting in the calander
				function createEvent ($client, $title = 'Tennis with Beth',
					$desc='Meet for a quick lesson', $where = 'On the courts',
					$startDate = '2009-03-04', $startTime = '10:00',
					$endDate = '2009-03-04', $endTime = '11:00', $tzOffset = '+01', $remindert, $tijd, $time, $kalender)
				{
						  $gdataCal = new Zend_Gdata_Calendar($client);
						  $newEvent = $gdataCal->newEventEntry();	
				
						  $newEvent->title = $gdataCal->newTitle($title);
						  $newEvent->where = array($gdataCal->newWhere($where));
						  $newEvent->content = $gdataCal->newContent("$desc");
						  
						 $when = $gdataCal->newWhen();
						 $when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
						 $when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
											  
						  $reminder = $gdataCal->newReminder();
    					  $reminder->setMethod($remindert);
						    if ($time == 'Minutes')
							  {
							  	$reminder->setMinutes($tijd);
							  }
						  if ($time == 'Hours')
							  {
							  	$reminder->setHours($tijd);
							  }
						  if ($time == 'Days')
							  {
							  	$reminder->setDays($tijd);
							  }
   						  $when->reminders = array($reminder); 
						  $newEvent->when = array($when);
			
						  // Upload the event to the calendar server
						  // A copy of the event as it is recorded on the server is returned
						  $createdEvent = $gdataCal->insertEvent($newEvent, $kalender);
						  return $createdEvent->id->text;
				}
			
			// getting EventID and breaking up the url
			$EventID = createEvent($client, "$Wat","$Beschrijving", "$Waar","$Bdatum", "$Btijd", "$Edatum","$Etijd", '+00', "$Reminder", "$Tijd", "$Time", $kalender);
			$urlparts = explode('/',$EventID);
			//say witch visibiulity each friend gets
			if(isset($_POST['check'])){
			$zichtbaarheid = $_POST['Zichtbaarheid'];
			$visibility = 'none';
				
			if($zichtbaarheid == 'Iedereen')
			  {
					$visibility = 'superpublic';
			  }
			elseif($zichtbaarheid == 'Hyvers')
			  {
					$visibility = 'public';
			  }
			elseif($zichtbaarheid == 'VvV')
			  {
					$visibility = 'friends_of_friends';
			  }
			elseif($zichtbaarheid == 'Vrieden')
			  {
					$visibility = 'friend';
			  }
				if ($visibility != 'none')
				 {
				 //inserting items to  calander
				   $sql = "INSERT INTO wwws (eventID, hyvesID, event, visibility, location, starttime) VALUES ('".$urlparts[8]."','".$_SESSION['hyvesid']."','".$Beschrijving."','".$visibility."','".$Waar."', '".$Bdatum." ".$Btijd."')";
			 mysql_query($sql, $db);
				 }
		 
		 
			
}			
			?>
			<div id="content">
            <div id="headert"><table><tr><td><img src="images/hyvessynclogo.png" title="HyvesSync" alt="HyvesSync" /></td><td><label class="title">HyvesSync</label></td></tr></table></div>

			<p>Het toevoegen van een agenda-item is gelukt. <a href="index1.php" onclick="laadscherm()">Ga terug</a> naar de hoofdpagina.</p>
			</div>
			<?php
			}
			else
			{
				?>
                <p>Helaas is er iets misgegaan bij het invullen van het formulier. Zie hieronder wat er aan de hand is.</p>
                <ul class="error"><?php echo $error; ?></ul>
                <div id="content">
                <div id="headert"><table><tr><td><img src="images/hyvessynclogo.png" title="HyvesSync" alt="HyvesSync" /></td><td><label class="title">HyvesSync</label></td></tr></table></div>
				<!--form for inserting in to the  calander-->
                </form>
                        <form method="post" action="invoegen.php">
                            <table>
								<tr>
									<td>
										Kalender: <br>
									</td>
									<td>
										<select name="Kalender" size="1">
												<?php
													for($i = 0; $i <= count($linkies); $i++)
													{
												?>
													  <option value="<?php echo $linkies[$i][0]; ?>">
													  <?php
													  echo $linkies[$i][1];
													  ?>
													  </option>
												<?php
													}
												?>
													  
										</select><br>
									</td>
								</tr>
                                <tr>
                                    <td>
                                        Wat: <br>
                                    </td>
                                    <td>
                                        <input type="text" name="Wat" value="<?php echo $_POST['Wat']; ?>"><br>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        Beschrijving: <br>
                                    </td>
                                    <td>
                                        <input type="text" name="Beschrijving" value="<?php echo $_POST['Beschrijving']; ?>"><br>
                                    </td>    
                                </tr>
                                <tr>
                                    <td>
                                        Waar: <br>
                                    </td>
                                    <td>    
                                        <input type="text" name="Waar" value="<?php echo $_POST['Waar']; ?>"><br><br>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        Begin datum:<br>
                                    </td>
                                    <td>
                                        <input type="text" id="begindatum" name="Bdatum" readonly="readonly" value="<?php echo $_POST['Bdatum']; ?>"><br>
                                    </td>
                                </tr>

                                <tr>
                                    <td>
                                        Eind datum:<br>
                                    </td>
                                    <td>    
                                        <input type="text" id="einddatum" name="Edatum" readonly="readonly" value="<?php echo $_POST['Edatum']; ?>"><br>
                                    </td>
                                </tr>
								<tr>
                                    <td>
                                        Begin tijd:<br>
                                    </td>
                                    <td>
                                       <div id="begintijd"><input type="hidden" name="Btijd" value="<?php echo $_POST['Btijd']; ?>"></div><br>
                                    <td>
                                </tr>
                                <tr>
                                    <td>
                                        Eind tijd:<br>
                                    </td>
                                    <td>    
                                       <div id="eindtijd"><input type="hidden" name="Etijd" value="<?php echo $_POST['Etijd']; ?>"></div><br>
                                    </td>
                                </tr>
                                <tr>
								<td>
									Reminder:<br>
									
									</td>
								<td>    
								<select name="Reminder" size="1">
									  <option value="sms">sms</option>
									  <option value="email">email</option>
									  <option value="alert">alert</option>
									  <option value="none" selected="selected">none</option>
								</select>
								
									<input id="Tijdje" type="text" name="Tijd" value="<?php echo $_POST['Tijd']; ?>">
									
								<select name="Time">
									   <option value="Minutes">Minuten</option>
									   <option value="Hours">Uren</option>
									   <option value="Days">Dagen</option>
							    </select>

							   </td>
							   </tr>
							   <tr>
                	<td>
                        Wie Wat Waar:<br>
                    </td>
                    <td>    
                       <?php
					   if (isset($_POST['www']))
					   {
					   ?>
					   <input type="checkbox" name="check" value="wwww" checked="checked" />
					   <?php
					   }
					   else
					   {
					   ?>
					   <input type="checkbox" name="check" value="wwww" />
					   <?php
					   }
					   ?>
					   <select name="Zichtbaarheid">
						   <option value="Iedereen">Iedereen</option>
						   <option value="Hyvers">Hyvers</option>
						   <option value="VvV">Vrienden van Vrienden</option>
						   <option value="Vrienden">Vrienden</option>
					   </select>
                    </td>
            	</tr>
               </table>
                                        
                            <input type="submit" name="Submit" value="Submit"><br><br><br>
                </form>
                <p><a href="index1.php" onclick="laadscherm()">Ga terug</a></p>
                </div>
                
                <?php
			
			}
}

else
{

?>
<div id="content">
<div id="headert"><table><tr><td><img src="images/hyvessynclogo.png" title="HyvesSync" alt="HyvesSync" /></td><td><label class="title">HyvesSync</label></td></tr></table></div>
<p>Vul hieronder de velden in om een agenda-item toe te voegen.</p>
</form>
		<form method="post" action="invoegen.php">
        	<table>
			    <tr>
                	<td>
                        Kalender: <br>
                    </td>
                    <td>
                        <select name="Kalender" size="1">
								<?php
									for($i = 0; $i <= count($linkies); $i++)
									{
								?>
									  <option value="<?php echo $linkies[$i][0]; ?>">
									  <?php
									  echo $linkies[$i][1];
									  ?>
									  </option>
								<?php
									}
								?>
									  
 						</select><br>
                    </td>
            	</tr>
            	<tr>
                	<td>
                        Wat: <br>
                    </td>
                    <td>
                        <input type="text" name="Wat"><br>
                    </td>
            	</tr>
                <tr>
                	<td>
                        Beschrijving: <br>
                    </td>
                    <td>
                        <input type="text" name="Beschrijving"><br>
                    </td>    
            	</tr>
                <tr>
                	<td>
						Waar: <br>
                    </td>
                    <td>    
						<input type="text" name="Waar"><br><br>
                    </td>
            	</tr>
                <tr>
                	<td>
                        Begin datum:<br>
                    </td>
                    <td>
                    	<input type="text" id="begindatum" name="Bdatum" readonly="readonly"><br>
                    </td>
            	</tr>
                <tr>
                	<td>
                        Eind datum:<br>
                    </td>
                    <td>    
                        <input type="text" id="einddatum" name="Edatum" readonly="readonly"><br>
                    </td>
            	</tr>
			    <tr>
                	<td>
                        Begin tijd:<br>
                    </td>
                    <td>
                       <div id="begintijd"><input type="hidden" name="Btijd" value="" /></div><br>
                    <td>
            	</tr>
                <tr>
                	<td>
                        Eind tijd:<br>
                    </td>
                    <td>    
                       <div id="eindtijd"><input type="hidden" name="Etijd" value="" /></div><br>
                    </td>
            	</tr>
                <tr>
					<td>
						Reminder:<br>
									
						</td>
								<td>    
								<select name="Reminder" size="1">
									  <option value="sms">sms</option>
									  <option value="email">email</option>
									  <option value="alert">alert</option>
									  <option value="none" selected="selected">none</option>
								</select>
								
									<input id="Tijdje" type="text" name="Tijd">
									
								<select name="Time">
									   <option value="Minutes">Minuten</option>
									   <option value="Hours">Uren</option>
									   <option value="Days">Dagen</option>
							    </select>

							   </td>
					 </tr>
				  <tr>
                	<td>
                        Wie Wat Waar:<br>
                    </td>
                    <td>    
                       
					   <input type="checkbox" name="check" value="www" />
					   
					   <select name="Zichtbaarheid">
						   <option value="Iedereen">Iedereen</option>
						   <option value="Hyvers">Hyvers</option>
						   <option value="VvV">Vrienden van Vrienden</option>
						   <option value="Vrienden">Vrienden</option>
					   </select>
                    </td>
            	</tr>
            </table>
						
			<input type="submit" name="Submit" value="Submit"><br><br><br>
</form>
<p><a href="index1.php" onclick="laadscherm()">Ga terug</a></p>
</div>

<?php
}
?>
</body>
</html>
